<template>
  <FullPageModal
    v-model:visible="innerVisible"
    custom-footer
    :title="t('aiot.serviceOrder.serviceDetail')"
    :get-container="getContainer"
    @open="open"
  >
    <div class="w-full">
      <div v-if="workRoleType" class="head-info flex flex-col items-center">
        <div
          class="state-info flex flex-row items-center h-16 mb-6 w-full"
          :style="{ background: stateColor, borderColor: stateColor }"
        >
          <p class="text-color-secondary pl-4">{{ t("aiot.serviceOrder.progressState") }}</p>
          <Icon v-if="iconStr.icon" :type="iconStr.icon" class="text-2xl pl-8" :style="{ color: iconStr.color }" />
          <p class="text-color-main font-semibold pl-1">{{ orderInfo.workOrderStateName }}</p>
        </div>
        <div class="state-step w-5/6">
          <a-steps
            :current="currentStep"
            progress-dot
            :initial="0"
            :class="orderInfo.workOrderState === 'CANCEL' ? 'cancel-step' : 'normal-step'"
          >
            <a-step v-for="(item, index) in stepArr" :key="item.workFlowNodeState">
              <template #description>
                <span class="timeline-desc"
                  >{{ item.createdOnShort }}
                  <div v-if="currentStep === 4 ? index === 3 : currentStep === index" class="arror-block"></div
                ></span>
              </template>
              <template #title>
                <div
                  class="text-color-secondary text-lg"
                  :class="currentStep === index ? ' font-semibold !text-color-main' : ''"
                  >{{ item.workFlowNodeStateName }}</div
                >
              </template>
            </a-step>
          </a-steps>
        </div>
        <div
          v-if="workFlowNodeRecord"
          class="state-step w-5/6 progress-text flex flex-row items-center mt-4 mb-4 arrow p-2"
          style="min-height: 3.5rem"
        >
          <p class="pl-4 m-0">{{ workFlowNodeRecord }}</p>
        </div>
      </div>
      <div class="flex flex-row">
        <OrderInfo
          v-model:recordArr="recordArr"
          v-model:orderDetails="orderDetails"
          v-model:showOrderInfoFlag="showOrderInfoFlag"
          v-model:workRoleType="operationType"
          :order-info="orderInfo"
          :get-container="getContainer"
          @success-fn="changePlannTime"
        />
      </div>
    </div>
    <template #footer>
      <div v-if="workRoleType" class="mr-6">
        <PermissionBtn
          v-if="orderInfo.evaluatesState === 'EVALUATED' && showBtnFn(orderInfo, BtnType.SEARCHEVALUATE, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('evaluateFn', orderInfo)"
          >{{ t("aiot.serviceOrder.viewEvaluate") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="orderInfo.visitState === 'VISITING' && showBtnFn(orderInfo, BtnType.VISIT, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('revisitFn', orderInfo)"
          >{{ t("aiot.serviceOrder.reVisit") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="orderInfo.visitState === 'VISITED' && showBtnFn(orderInfo, BtnType.SEARCHEVISIT, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('viewVisit', orderInfo)"
          >{{ t("aiot.serviceOrder.viewVisit") }}</PermissionBtn
        >
        <!-- 运营按钮 -->
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.REFUSE, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('workOrderFn', orderInfo, BtnType.REFUSE)"
          >{{ t("aiot.serviceOrder.rejectWorkOrders") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.RECEIVING, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('workOrderFn', orderInfo, BtnType.RECEIVING)"
          >{{ t("aiot.serviceOrder.receivingWorkOrders") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.TURNBACK, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('workOrderFn', orderInfo, BtnType.TURNBACK)"
          >{{ t("aiot.serviceOrder.reback") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.TURNDISPATCH, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('dispatch', orderInfo, BtnType.TURNDISPATCH)"
          >{{ t("aiot.serviceOrder.transWorkOrder") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.EXECUTE, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('workOrderFn', orderInfo, BtnType.EXECUTE)"
          >{{ t("aiot.serviceOrder.excute") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.CONSTRUCTION, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('constructFn', orderInfo)"
          >{{ t("aiot.serviceOrder.constructionWorkOrders") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.FINISH, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('finishFn', orderInfo)"
          >{{ t("aiot.serviceOrder.finishWorkOrders") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.CANCEL, workRoleType) || orderInfo.workOrderState === BtnType.DISPATCH"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('cancelFn', orderInfo)"
          >{{ t("common.cancel") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.DISPATCH, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('dispatch', orderInfo, BtnType.DISPATCH)"
          >{{ t("aiot.serviceOrder.dispatchWorkOrder") }}</PermissionBtn
        >
        <PermissionBtn
          v-if="showBtnFn(orderInfo, BtnType.REASSIGNMENT, workRoleType)"
          class="permissonRef"
          :oper-type="OperPermissionType.MANAGE"
          :route-name="routeName"
          style="margin-left: 1.5rem"
          @click="emits('dispatch', orderInfo, BtnType.REASSIGNMENT)"
          >{{ t("aiot.serviceOrder.changeDispatch") }}</PermissionBtn
        >
      </div>
    </template>
  </FullPageModal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import OrderInfo from "./OrderInfo.vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import { useWorkOrderModal } from "./useWorkOrderModal";
import { OperPermissionType } from "/@/api/aiot/role/models";
import {
  createWorkOrders,
  getWorkOrderRecords,
  getWorkOrdersById,
  getWorkFlowNodes,
  getWorkOrderSignInsByWorkOrderId,
  getConstructionsByWorkOrderId,
  getCompletedsByWorkOrderId,
} from "/@/api/aiot/serviceWorkOrder";
import {
  OrderDetails,
  RecordItem,
  WorkFlowNode,
  WorkOrderInfo,
  WorkOrderItem,
  BtnType,
  FlowNoeReq,
} from "/@/api/aiot/serviceWorkOrder/models";
import { useOrderModal } from "./useOrderModal";
function setBtnColor() {
  let permissonRef = document.getElementsByClassName("permissonRef");
  var lastChild: any = permissonRef[permissonRef.length - 1];
  if (lastChild && lastChild.children[0]) {
    lastChild.children[0].style.color = "#fff";
    lastChild.children[0].style.borderColor = "#4285f4";
    lastChild.children[0].style.background = "#4285f4";
  }
}
const emits = defineEmits([
  "create",
  "update:visible",
  "ok",
  "dispatch",
  "cancelFn",
  "evaluateFn",
  "revisitFn",
  "viewVisit",
  "workOrderFn",
  "constructFn",
  "finishFn",
  "successFn",
]);
const { t } = useI18n();
const props = defineProps<{
  visible: boolean;
  worksOrderId?: string;
  workRoleType?: string;
  routeName?: string;
  getContainer?: () => HTMLElement;
}>();
const showOrderInfoFlag = ref<boolean>(false);
// const currentStep = shallowRef<number>(0);
const operationType = computed(() => {
  return props.workRoleType;
});
const { showBtnFn } = useOrderModal();
const orderInfo = ref<WorkOrderInfo>({});
const stepColor = ref<string>("#fd8358");
const recordArr = ref<Array<RecordItem>>([]);
const workFlowNodes = ref<Array<WorkFlowNode>>([]);
const { workOrderIns, model, modelFormSetting } = useWorkOrderModal();
const innerVisible = ref(false);
// const stepColor = computed(() => {
//   if (orderInfo.value.workOrderState === "CANCEL") {
//     return "#fd8358";
//   } else {
//     return "#3ddc84";
//   }
// });
const currentStep = computed(() => {
  let indexArr = workFlowNodes.value.map((item, index) => {
    return item.workOrderId ? index : -1;
  });
  if (Math.max(...indexArr) === 3) {
    return 3;
  }
  // else if (orderInfo.value.workOrderState === "CANCEL") {
  //   return -2;
  // }
  else {
    return Math.max(...indexArr);
  }
});
const stateColor = computed(() => {
  let StateColorArr = {
    "-2": "rgba(123,135,154, 0.1)",
    "-1": "rgba(245, 109, 106, 0.1)",
    "0": "rgba(253,131,88, 0.1)",
    "1": "rgba(57, 201, 225, 0.1)",
    "2": "rgba(75, 139, 244, 0.1)",
    "3": "rgba(73, 204, 144, 0.1)",
    "4": "rgba(73, 204, 144, 0.1)",
  };
  if (!isNaN(currentStep.value)) {
    return StateColorArr[currentStep.value];
  } else {
    return "";
  }
});
const iconStr = computed(() => {
  return {
    icon: {
      DISPATCH: "icon-dengdai",
      WAITING: "icon-dengdai",
      EXECUTE: "icon-dengdai",
      OVER: "icon-jinggao",
      PROGRESS: "icon-dengdai",
      CONSTRUCTION: "icon-dengdai",
      FINISHED: "icon-yiwancheng",
      EVALUATED: "icon-yipingjia",
      CANCEL: "icon-yiquxiao",
    }[orderInfo.value.workOrderState || ""],
    color: {
      DISPATCH: "rgba(245,109,106,1)",
      WAITING: "rgba(253,131,88,1)",
      EXECUTE: "rgba(57,201,225,1)",
      OVER: "rgba(245,184,60,1)",
      PROGRESS: "rgba(75,139,244,1)",
      CONSTRUCTION: "rgba(75,139,244,1)",
      FINISHED: "rgba(56,206,123, 1)",
      CANCEL: "rgba(253,131,88,1)",
    }[orderInfo.value.workOrderState || ""],
  };
});
var stepArr = ref<Array<WorkFlowNode>>([]);

const orderDetails = ref<OrderDetails>({
  signinInfo: [],
  constructionInfo: {},
  completeInfo: {},
});
const workFlowNodeRecord = ref<string>("");
watch(
  () => props.visible,
  async (v) => {
    innerVisible.value = v;
    await init();
    setBtnColor();
  }
);
async function init() {
  if (props.visible) {
    let obj = { workOrderId: props.worksOrderId, worksOrderId: props.worksOrderId, workRoleType: props.workRoleType };
    // 获取签到信息
    orderDetails.value.signinInfo = (await getWorkOrderSignInsByWorkOrderId(obj)) || [];
    // 获取施工信息
    orderDetails.value.constructionInfo = (await getConstructionsByWorkOrderId(obj)) || {};
    // 获取完工信息
    orderDetails.value.completeInfo = (await getCompletedsByWorkOrderId(obj)) || {};
    let req = await getWorkOrdersById(obj);
    if (props.workRoleType) {
      let flowNodes: FlowNoeReq | null = await getWorkFlowNodes(obj);
      workFlowNodeRecord.value = flowNodes?.workFlowNodeRecord || "";
      workFlowNodes.value = flowNodes?.traceNodeDetailResponses || [];
      stepArr.value = workFlowNodes.value.map((item) => {
        return {
          workFlowNodeState: item.workFlowNodeState,
          workFlowNodeStateName: item.workFlowNodeStateName,
          createdOnShort: item.createdOnShort,
        };
      });
    }
    recordArr.value = (await getWorkOrderRecords(obj)) || [];
    showOrderInfoFlag.value = true;
    orderInfo.value = req || {};
  } else {
    orderInfo.value = {};
  }
}
// function getContainer() {
//   return document.body;
// }
function open() {
  nextTick(() => {
    workOrderIns.value?.initFormItemComponentData();
  });
  showOrderInfoFlag.value = false;
}
//第一次打开
let firstShow = true;
watch(innerVisible, (v) => {
  emits("update:visible", v);
  if (firstShow) {
    firstShow = false;
  }
});
async function changePlannTime() {
  await init();
  setBtnColor();
  emits("successFn");
}
//窗口关闭
function cancel() {
  emits("update:visible", false);
}

async function ok(isContinue) {
  workOrderIns.value?.validate().then(async () => {
    model.value.faultImages = [];
    let data: WorkOrderItem = { ...model.value };
    let req = await createWorkOrders(data);
    req && emits("ok");
  });
}
</script>
<style lang="less" scoped>
.state-info {
  background: rgba(57, 201, 225, 0.1);
  border-radius: 4px;
  border: 1px solid #39c9e1;
  p {
    margin: 0;
  }
}
.progress-text {
  border: 1px solid #e9ebee;
  > p {
    font-size: 14px;
    color: #172b4d;
    line-height: 22px;
    font-weight: 400;
  }
}
// fd8358
:deep(.cancel-step > .ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-tail::after) {
  background-color: #f0f0f0;
}
:deep(.cancel-step > .ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot) {
  background: #fd8358;
}
:deep(.cancel-step > .ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot) {
  background: #f0f0f0;
}
:deep(.normal-step > .ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-tail::after) {
  background-color: #f0f0f0;
}
:deep(.normal-step > .ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot) {
  background: #3ddc84;
}
:deep(.normal-step > .ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot) {
  background: #f0f0f0;
}
:deep(.ant-steps-dot .ant-steps-item-tail::after, .ant-steps-dot.ant-steps-small .ant-steps-item-tail::after) {
  height: 1px;
}
.arrow {
  position: relative;
  z-index: 1000;
}
.arrow-block {
  content: "";
  display: block;
  position: absolute;
  top: -7px;
  // left: calc(406px - 0px);
  left: 40px;
  height: 0.8rem;
  width: 0.8rem;
  border-top: 1px solid #e9ebee;
  border-right: 1px solid #e9ebee;
  transform: rotate(-45deg);
  z-index: 999;
  background: #fff;
}
.arror-block {
  display: block;
  position: absolute;
  top: 73px;
  // left: calc(406px - 0px);
  left: 66px;
  height: 0.8rem;
  width: 0.8rem;
  border-top: 1px solid #e9ebee;
  border-right: 1px solid #e9ebee;
  transform: rotate(-45deg);
  z-index: 1002;
  background: #fff;
}
.permissonRef:last-child {
  // background: #39c9e1;
  button {
    color: #fff;
    border-color: #4285f4;
    background: #4285f4;
  }
}
</style>
